package com.pattern.parallel.completableFuture;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.logging.Logger;
import java.util.stream.Collectors;

public class CompletableFutureDemo2 {

    public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();
        ExecutorService executor = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(),
                Runtime.getRuntime().availableProcessors() * 2, 120, TimeUnit.SECONDS, new LinkedBlockingDeque<>(200));
        List<DemoDto> dtoList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            dtoList.add(new DemoDto());
        }
        //采用Stream流的形式进行处理
        List<CompletableFuture<DemoDto>> priceFuture = dtoList.stream().map(dto -> CompletableFuture
                .supplyAsync(() -> doWork(dto), executor))
                .collect(Collectors.toList());
        List<DemoDto> list = priceFuture.stream().map(CompletableFuture::join).collect(Collectors.toList());
        executor.shutdown();
        for (DemoDto dto: list) {
            System.out.println(dto.getThreadName());
        }
        System.out.println("batchInsertAEmployee 共耗时：" + (System.currentTimeMillis() - start));

        /*long start = System.currentTimeMillis();
        for (int i =0; i<8; i++) {
            doWork(new DemoDto());
        }
        System.out.println("batchInsertAEmployee 共耗时：" + (System.currentTimeMillis() - start));*/
    }

    private static DemoDto doWork(DemoDto dto) {
        dto.setThreadName(Thread.currentThread().getName());
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return dto;
    }

}
